package com.originskyseed.platform.cms.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.cms.i18n.CmsResponseMsg;
import com.originskyseed.platform.cms.model.CmsProductInfo;
import com.originskyseed.platform.cms.service.ICmsProductInfoService;
import com.originskyseed.platform.cms.vo.request.CmsProductInfoRequestVO;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.model.UserInfo;

/**
 * 产品信息表Controller类（OSI_PRODUCT_INFO）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/cmsProductInfo")
@BaseLocaleResource(localeFileName = "i18n_cms")
public class CmsProductInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CmsProductInfoController.class);

	@DubboReference
	private ICmsProductInfoService cmsProductInfoService;

	/**
	 * 产品列表_分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsProductInfoList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody cmsProductInfoList(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求对象
			int pageNo = this.getParameterInteger("pageNo", 1);
			int pageSize = this.getParameterInteger("pageSize", 10);
			String type = this.getParameterString("type", "");
			String name = this.getParameterString("name", "");
			BasePage<CmsProductInfo> page = new BasePage<CmsProductInfo>(pageNo, pageSize);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			if (type == null || StringUtils.isEmpty(type)) {
				if (userInfo == null || userInfo.getOtherAccount() == null || StringUtils.isEmpty(userInfo.getOtherAccount())) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.BUSINESS_BIND_ISNULL.getMsg()), null);
				}
				List<CmsProductInfo> cmsProductInfoList = new ArrayList<>();

				// 请求接口
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("channelId", userInfo.getOtherAccount());
				Map resultMap = QueryAppUtil.query("appInfoUrl", 1, paramMap);
				Integer code = Integer.parseInt(resultMap.get("code").toString());
				String msg = (String) resultMap.get("msg");
				if (code == 1) {
					// json字符串转jsonArray
					String data = (String) resultMap.get("data");
					cmsProductInfoList = JsonUtils.parseArray(data, CmsProductInfo.class);
					if (name != null && StringUtils.isNotEmpty(name)) {
						if (cmsProductInfoList != null && cmsProductInfoList.size() > 0) {
							for (int i = 0; i < cmsProductInfoList.size(); i++) {
								if (cmsProductInfoList.get(i).getName().indexOf(name) > -1) {
									continue;
								} else {
									cmsProductInfoList.remove(i);
									i--;
								}
							}
						}

					}
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
				}
				// 分页查询
				List<CmsProductInfo> tempList = this.startPage(cmsProductInfoList, pageNo, pageSize);
				page.setResults(tempList);
				int count = cmsProductInfoList == null ? 0 : cmsProductInfoList.size();
				page.setTotalPage(count == 0 ? 0 : count / pageSize + 1);
				page.setTotalRecord(count);
			} else {
				// 请求对象
				/*
				 * StringBuilder typeStringBuilder=new StringBuilder(); List<String> typeList=Arrays.asList(type); if(typeList!=null&&typeList.size()>0) { for(int i=0;i<typeList.size();i++) { typeStringBuilder.append("'"+typeList.get(i)+"',"); } } String typeStr=typeStringBuilder.toString(); if(typeStr!=null&&StringUtils.isNotEmpty(typeStr)) { typeStr=typeStr.substring(0,typeStr.length()-1); }
				 */
				CmsProductInfoRequestVO requestVO = this.getParameterBean(CmsProductInfoRequestVO.class);
				requestVO.setTypeStr(type);
				List<Integer> typeList = new ArrayList<>();
				Map map = requestVO.toMap();
				map.remove("type");
				String[] typeArr = type.split(",");
				for (int i = 0; i < typeArr.length; i++) {
					typeList.add(Integer.parseInt(typeArr[i]));
				}
				map.put("typeList", typeList);
				page = this.cmsProductInfoService.selectListByPage(map, page);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_PRODUCT_INFO_LIST_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_PRODUCT_INFO_LIST_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询产品信息详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectDetailsById.json")
	@RequiredParams(names = { "id" })
	public BaseResponseBody<CmsProductInfo> selectDetailsById(HttpServletRequest request) {
		BaseResponseBody<CmsProductInfo> result = null;
		try {
			// 请求对象
			String id = this.getParameterString("id", null);
			String type = this.getParameterString("type", null);
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			CmsProductInfo cmsProductInfo = new CmsProductInfo();
			if (type != null && StringUtils.isNotEmpty(type)) {
				cmsProductInfo = this.cmsProductInfoService.selectByPrimaryKey(id);
			} else {
				List<CmsProductInfo> cmsProductInfoList = new ArrayList<>();
				if (userInfo == null || userInfo.getOtherAccount() == null || StringUtils.isEmpty(userInfo.getOtherAccount())) {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.BUSINESS_BIND_ISNULL.getMsg()), null);
				}
				TreeMap<String, Object> paramMap = new TreeMap<>();
				paramMap.put("channelId", userInfo.getOtherAccount());
				Map resultMap = QueryAppUtil.query("appInfoUrl", 1, paramMap);
				Integer code = Integer.parseInt(resultMap.get("code").toString());
				String msg = (String) resultMap.get("msg");
				if (code == 1) {
					// json字符串转jsonArray
					String data = (String) resultMap.get("data");
					cmsProductInfoList = JsonUtils.parseArray(data, CmsProductInfo.class);
				} else {
					return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), msg, null);
				}
				if (cmsProductInfoList != null && cmsProductInfoList.size() > 0) {
					for (int i = 0; i < cmsProductInfoList.size(); i++) {
						if (cmsProductInfoList.get(i).getProductId().equals(id)) {
							cmsProductInfo = cmsProductInfoList.get(i);
							break;
						}
					}
				}
			}
			result = new BaseResponseBody<CmsProductInfo>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_SUCCESS.getMsg()), cmsProductInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsProductInfo>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsProductInfoSave.json")
	@RequiredParams(names = {})
	public BaseResponseBody<CmsProductInfo> cmsProductInfoSave(HttpServletRequest request) {
		BaseResponseBody<CmsProductInfo> result = null;
		try {
			// 请求对象
			CmsProductInfo cmsProductInfo = this.getParameterBean(CmsProductInfo.class);
			if (StringUtils.isNotBlank(cmsProductInfo.getId())) {
				this.cmsProductInfoService.updateByPrimaryKey(cmsProductInfo);
			} else {
				String key = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
				cmsProductInfo.setId(key);
				cmsProductInfo.setIsDel(2);
				this.cmsProductInfoService.insertSelective(cmsProductInfo);
			}
			result = new BaseResponseBody<CmsProductInfo>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_PRODUCT_INFO_SAVE_SUCCESS.getMsg()), cmsProductInfo);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<CmsProductInfo>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.CMS_PRODUCT_INFO_SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/cmsProductInfoDelete.json")
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> cmsProductInfoDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.cmsProductInfoService.falseDeleteByPrimaryKeys(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CmsResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 自定义分页
	 *
	 * @param list
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	private List<CmsProductInfo> startPage(List<CmsProductInfo> list, Integer pageNum, Integer pageSize) {
		if (list == null) {
			return null;
		}
		if (list.size() == 0) {
			return null;
		}

		Integer count = list.size(); // 记录总数
		Integer pageCount = 0; // 页数
		if (count % pageSize == 0) {
			pageCount = count / pageSize;
		} else {
			pageCount = count / pageSize + 1;
		}

		int fromIndex = 0; // 开始索引
		int toIndex = 0; // 结束索引

		if (pageNum != pageCount) {
			fromIndex = (pageNum - 1) * pageSize;
			toIndex = fromIndex + pageSize;
		} else {
			fromIndex = (pageNum - 1) * pageSize;
			toIndex = count;
		}

		List<CmsProductInfo> pageList = list.subList(fromIndex, toIndex);

		return pageList;
	}

}
